var ajaxResponseObj;
var REQUEST_DATA = {
  displayName: '',
  email: '',
  password: '',
  passwordConfirm: '',
  action: ''
}

function UserLogIn()
{
  REQUEST_DATA.email = $('#formLoginUser_email').val();
  REQUEST_DATA.password = $('#formLoginUser_password').val();
  REQUEST_DATA.action = "user-logIn";

  $.ajax({
    type: "POST",
    url: "../../../admin/api/UserRegistration.php",
    data: REQUEST_DATA,
    success: RegistrationSuccess
  });
}

function UserLogOut()
{
  REQUEST_DATA.action = "logout";
  $.ajax({
    type: "POST",
    url: "../../../admin/api/UserRegistration.php",
    data: REQUEST_DATA,
    success: RegistrationSuccess
  });
}

function DataValidation()
{
  var bool = true;
  for(var el in REQUEST_DATA )
  {
    var path = '#formRegisterUser_' + el + '-label .field-error';
    if(REQUEST_DATA[el] == '')
    {
      bool = false;
      $(path).text('Acest cimp nu poate fi gol!');
    }
  }
  return bool;
}

function PasswordValidation()
{
  if(REQUEST_DATA['password'] != REQUEST_DATA['passwordConfirm'])
  {
    $('#formRegisterUser_password-label .field-error').text('Parola introdusa nu este validă');
    return false;
  }
  else
    return true;
}

function EmailValidation()
{
  var object = REQUEST_DATA['email'].match(/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/);
  
  if(!object)
  {
    $('#formRegisterUser_email-label .field-error').text('Adresa de email introdusă nu este validă.');
    return false;
  }
  
  return true;
}

function UserRegistration()
{
  $('#formRegisterUser').find('.field-error').text('');
  REQUEST_DATA.displayName = $('#formRegisterUser_displayName').val();
  REQUEST_DATA.email = $('#formRegisterUser_email').val();
  REQUEST_DATA.password = $('#formRegisterUser_password').val();
  REQUEST_DATA.passwordConfirm = $('#formRegisterUser_passwordConfirm').val();
  REQUEST_DATA.action = 'user-registration';
  
  if(DataValidation() && PasswordValidation() && EmailValidation())
  {
    $.ajax({
      type: "POST",
      url: "../../../admin/api/UserRegistration.php",
      data: REQUEST_DATA,
      success: RegistrationSuccess
    });
  }
}

function RegistrationSuccess(response)
{
  ajaxResponseObj = eval('(' + response + ')');
  var data = ajaxResponseObj;
  if(data['code'] == 200)
    window.location.href = 'http://localhost:200/index.php';
  else
    $('#formLoginUser_password-label .field-error').text(data['message']);

}